﻿namespace _5_NovaAdmin.Infrastructure.Persistence.UnitOfWork;

/// <summary>
/// 工作单元实现
/// </summary>
/// <typeparam name="TDbContext"></typeparam>
public class UnitOfWork<TDbContext> : IUnitOfWork where TDbContext : DbContext
{

    private readonly TDbContext _Mddb;
    private readonly IMediator _mediator;

    public UnitOfWork(TDbContext context, IMediator mediator)
    {
        _Mddb = context ?? throw new ArgumentNullException(nameof(context));
        _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
    }

    public async Task<bool> SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        await _Mddb.SaveChangesAsync();
        // 默认返回true，表示保存成功。如果发生异常，不在这里进行异常处理，而是让调用者处理
        return true;
    }

    public async Task<int> SaveEntitiesAsync(CancellationToken cancellationToken = default)
    {
        // 处理DbContext中的领域事件
        await _mediator.DispatchDomainEventsAsync(_Mddb);
        // 调用基类的 SaveChangesAsync 方法，将更改保存到数据库
        return await _Mddb.SaveChangesAsync(cancellationToken);
    }
}
